// 导入验证插件
import wxValidate from 'wechat-validate'
Page({
  behaviors: [wxValidate],
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    currentDate: Date.now(),
    maxDate: Date.now() + 1000 * 3600 * 24 * 3, // 最大时间
    houseList: [],
    "houseInfo": "",
    "houseId": "",
    "name": "",
    "gender": 1,
    "mobile": "",
    "visitDate": ""
  },
  rules: {
    name: [
      { required: true, message: '访客姓名不能为空!' },
      { pattern: /[\u4e00-\u9fa5]{2,5}/, message: '访客姓名只能为中文!' },
    ],
    mobile: [
      { required: true, message: '访客手机号不能为空!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!' },
    ],
    houseId: [
      { required: true, message: '请选择到访的房屋!' }
    ],
    visitDate: [
      { required: true, message: '请选择到访的日期!' }
    ],
  },
  onLoad() {
    this.getHouseList()
  },
  // 获取房屋列表
  async getHouseList() {
    let houseList = await wx.http.get('/room')
    console.log(houseList)
    houseList = houseList.map(item => ({
      name: item.point + item.building + item.room,
      id: item.id
    }))
    this.setData({ houseList })
  },
  // 选择了房屋
  selectHouse({ detail }) {
    this.setData({ houseId: detail.id, houseInfo: detail.name })
  },
  // 选择了时间
  selectDateInfo(event) {
    // event.detail 获取到选择的日期
    this.setData({
      visitDate: wx.utils.dataFormAt(event.detail),
      dateLayerVisible: false
    })
  },

  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  // 表单数据提交
  async goPassport() {
    // 1.表单校验
    const isPass = this.validate()
    if (!isPass) return
    // 2.提交数据
    const { name, mobile, visitDate, gender, houseId } = this.data
    let res = await wx.http.post('/visitor', {
      name, mobile, visitDate, gender, houseId
    })
    console.log(res);
    // 3.提示成功
    wx.utils.toast('操作成功')
    // 4.跳转页面
    setTimeout(() => {
      wx.reLaunch({
        url: '/visitor_pkg/pages/passport/index?id=' + res.id,
      })
    }, 300)
  },
})
